package api

import (
	"encoding/json"
	"fmt"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// BookingController 预约订单控制器
type BookingController struct {
	web.Controller
}

// UpdateStatus 更新订单状态
func (c *BookingController) UpdateStatus() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		Id     int64 `json:"id"`
		Status int8  `json:"status"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetOrderById(req.Id)
	if err != nil || order == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证订单是否属于当前用户
	if order.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该订单",
		}
		c.ServeJSON()
		return
	}

	// 更新订单状态
	err = models.UpdateOrderStatus(req.Id, req.Status, "用户确认到店", member.Phone)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新订单状态失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "操作成功",
	}
	c.ServeJSON()
}

// 检查时间段是否可预约
func checkTimeSlotAvailable(venueId int64, startTime, endTime int64) (bool, string) {
	// 转换Unix时间戳为Time对象
	startDateTime := time.Unix(startTime, 0)
	endDateTime := time.Unix(endTime, 0)

	// 获取场地信息
	venue, err := models.GetVenueById(venueId)
	if err != nil {
		return false, "获取场地信息失败"
	}

	// 获取门店信息
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil {
		return false, "获取门店信息失败"
	}

	// 解析营业时间
	businessHours := store.BusinessHours
	if businessHours == "" {
		businessHours = `{"start":"00:00","end":"23:59"}` // 默认营业时间
	}

	// 解析营业时间JSON
	var hours struct {
		Start string `json:"start"`
		End   string `json:"end"`
	}
	err = json.Unmarshal([]byte(businessHours), &hours)
	if err != nil {
		return false, "解析营业时间失败"
	}

	// 解析营业开始时间
	startHourStr := hours.Start
	var startHour, startMinute int
	if len(startHourStr) >= 5 {
		startHour, _ = strconv.Atoi(startHourStr[0:2])
		startMinute, _ = strconv.Atoi(startHourStr[3:5])
	} else {
		startHour = 0 // 默认9点开始
		startMinute = 0
	}

	// 解析营业结束时间
	endHourStr := hours.End
	var endHour, endMinute int
	if len(endHourStr) >= 5 {
		endHour, _ = strconv.Atoi(endHourStr[0:2])
		endMinute, _ = strconv.Atoi(endHourStr[3:5])
	} else {
		endHour = 24 // 默认22点结束
		endMinute = 0
	}

	// 检查预约时间是否在营业时间内
	bookingStartHour := startDateTime.Hour()
	bookingStartMinute := startDateTime.Minute()
	bookingEndHour := endDateTime.Hour()
	bookingEndMinute := endDateTime.Minute()

	// 开始时间检查
	if bookingStartHour < startHour || (bookingStartHour == startHour && bookingStartMinute < startMinute) {
		return false, "预约开始时间早于营业时间"
	}

	// 结束时间检查
	if bookingEndHour > endHour || (bookingEndHour == endHour && bookingEndMinute > endMinute) {
		return false, "预约结束时间晚于营业时间"
	}

	// 检查场地状态是否可用
	if venue.Status != 1 {
		return false, "该场地当前不可预约"
	}

	// 获取预约当天日期
	_ = time.Date(startDateTime.Year(), startDateTime.Month(), startDateTime.Day(), 0, 0, 0, 0, time.Local)

	// 查询数据库中是否有重叠的预约
	o := models.GetOrm()
	count, err := o.QueryTable(new(models.Order)).
		Filter("venue_id", venueId).
		Filter("status__in", models.BookingStatusPending, models.BookingStatusConfirmed). // 待确认或已确认的订单
		Filter("is_deleted", 0).
		Filter("start_time__lt", endTime). // 开始时间小于请求的结束时间
		Filter("end_time__gt", startTime). // 结束时间大于请求的开始时间
		Count()

	if err != nil {
		return false, "系统错误，请稍后再试"
	}

	if count > 0 {
		return false, "该时间段已被预约"
	}

	return true, ""
}

// Create 创建预约订单
func (c *BookingController) Create() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		StoreId       string `json:"store_id"`       // 门店ID
		VenueId       int64  `json:"venue_id"`       // 场地ID
		StartTime     int64  `json:"start_time"`     // 开始时间戳
		EndTime       int64  `json:"end_time"`       // 结束时间戳
		TotalAmount   int64  `json:"total_amount"`   // 总金额（分）
		GroupBuyId    int64  `json:"group_buy_id"`   // 团购券ID
		CouponId      int64  `json:"coupon_id"`      // 优惠券ID
		UseBalance    int64  `json:"use_balance"`    // 是否使用余额 1:使用 0:不使用
		BalanceAmount int64  `json:"balance_amount"` // 使用余额金额（分）
		Remark        string `json:"remark"`         // 备注
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.VenueId <= 0 || req.StartTime <= 0 || req.EndTime <= 0 || req.StartTime >= req.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预约参数有误",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(req.VenueId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查时间段是否可预约
	available, message := checkTimeSlotAvailable(req.VenueId, req.StartTime, req.EndTime)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 生成订单号
	orderNo := models.GenerateOrderNo("B")

	// 计算实际需要支付的金额（总金额减去余额支付部分）
	remainingAmount := req.TotalAmount
	payChannel := "wechat"
	balanceAmount := int64(0)
	useBalance := int8(0)
	// 如果使用余额支付
	if req.UseBalance == 1 && req.BalanceAmount > 0 {
		// 检查会员余额是否足够
		memberBalance := int64(member.Balance * 100) // 转换为分

		// 如果余额不足，使用全部余额
		if memberBalance < req.BalanceAmount {
			balanceAmount = memberBalance
			payChannel = "balance+wechat"
		} else {
			balanceAmount = req.BalanceAmount
			payChannel = "balance"
		}

		// 计算剩余需要支付的金额
		remainingAmount = req.TotalAmount - balanceAmount
		useBalance = 1
	}

	// 创建预约订单
	booking := &models.Order{
		OrderNo:        orderNo,
		UserId:         member.Id,
		MemberId:       member.Id,
		UserName:       member.Name,
		Phone:          member.Phone,
		Type:           0,                           // 预约订单类型
		Status:         models.BookingStatusPending, // 待确认
		BalanceAmount:  balanceAmount,
		UseBalance:     useBalance, // 1:使用 0:不使用
		TotalAmount:    req.TotalAmount,
		PayAmount:      remainingAmount, // 实际需要支付的金额
		PaymentChannel: payChannel,      // 预约订单可能不需要支付
		PaymentStatus:  1,               // 未支付
		VenueId:        req.VenueId,
		StoreId:        venue.StoreId,
		StartTime:      req.StartTime,
		EndTime:        req.EndTime,
		Remark:         req.Remark,
	}

	// 如果有团购券，处理团购券逻辑
	if req.GroupBuyId > 0 {
		// 处理团购券使用逻辑
		// 此处需要检查团购券是否有效，并标记为已使用
		booking.GroupBuyId = req.GroupBuyId
	}

	// 如果有优惠券，处理优惠券逻辑
	if req.CouponId > 0 {
		// 处理优惠券使用逻辑
		// 此处需要检查优惠券是否有效，并标记为已使用
		booking.CouponId = req.CouponId
	}

	// 设置基础字段
	now := time.Now().Unix()
	booking.CreatedAt = now
	booking.UpdatedAt = now

	// 开启事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		logs.Error("开启事务失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 保存订单到数据库
	id, err := models.CreateBookingTx(tx, booking)
	if err != nil {
		tx.Rollback()
		logs.Error("创建预约订单失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建预约订单失败",
		}
		c.ServeJSON()
		return
	}

	// 如果使用余额支付，更新会员余额
	if req.UseBalance == 1 && balanceAmount > 0 {
		// 将分转换为元
		balanceAmountYuan := float64(balanceAmount) / 100

		// 更新会员余额（减少余额）
		err = models.UpdateMemberBalanceWithLogTx(tx, member.Id, -balanceAmountYuan, 2, orderNo, "", "场地预约-余额支付", "系统", member.FranchiseId)
		if err != nil {
			tx.Rollback()
			logs.Error("更新会员余额失败: %v", err)
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "余额支付失败，请稍后再试",
			}
			c.ServeJSON()
			return
		}

		// 如果整个订单都用余额支付了，更新订单支付状态为已支付
		if remainingAmount == 0 {
			booking.Id = id
			booking.PaymentStatus = 1          // 已支付
			booking.PaymentChannel = "balance" // 支付渠道为余额
			booking.PaymentTime = now

			_, err = models.UpdateOrderTx(tx, booking, "PaymentStatus", "PaymentChannel", "PaymentTime")
			if err != nil {
				tx.Rollback()
				logs.Error("更新订单支付状态失败: %v", err)
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "更新订单状态失败，请稍后再试",
				}
				c.ServeJSON()
				return
			}
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		logs.Error("提交事务失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "预约成功",
		"data": map[string]interface{}{
			"id":            id,
			"order_no":      orderNo,
			"balance_used":  balanceAmount,
			"remaining_pay": remainingAmount,
			"payment_status": func() int {
				if remainingAmount == 0 {
					return 1
				} else {
					return 0
				}
			}(), // 如果余额完全支付，则支付状态为已支付
			"payment_channel": func() string {
				if remainingAmount == 0 {
					return "balance"
				} else {
					return "wechat"
				}
			}(),
		},
	}
	c.ServeJSON()
}

// List 获取预约订单列表
func (c *BookingController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("page_size"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	statusStr := c.GetString("status")
	var status interface{}
	if statusStr != "" {
		// 检查是否为数组格式 [2,3]
		var statusArray []int8
		err := json.Unmarshal([]byte(statusStr), &statusArray)
		if err == nil && len(statusArray) > 0 {
			status = statusArray
		} else {
			// 尝试解析为单个整数
			statusVal, err := strconv.ParseInt(statusStr, 10, 8)
			if err == nil {
				status = int8(statusVal)
			}
		}
	}

	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["user_id"] = member.Id

	if status != nil {
		filters["status"] = status
	}

	storeId := c.GetString("store_id")
	if storeId != "" {
		filters["store_id"] = storeId
	}

	startTimeStr := c.GetString("start_time")
	if startTimeStr != "" {
		startTime, err := strconv.ParseInt(startTimeStr, 10, 64)
		if err == nil {
			// 假设模型使用 created_at 进行筛选
			filters["created_at__gte"] = startTime
		}
	}

	// 查询预约订单列表
	bookings, total, err := models.GetBookingList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预约订单列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取关联的场地信息并扩展订单数据
	type extendedBooking struct {
		*models.Order
		VenueName  string `json:"venue_name"`
		VenueImage string `json:"venue_image"`
	}

	extendedList := make([]*extendedBooking, 0, len(bookings))

	for _, booking := range bookings {
		// 扩展订单信息，添加场地名称
		extended := &extendedBooking{
			Order:      booking,
			VenueName:  booking.StoreName, // 默认使用门店名称
			VenueImage: "",                // 默认空图片路径
		}

		// 如果有关联场地，尝试获取场地信息
		if booking.VenueId > 0 {
			venue, err := models.GetVenueById(booking.VenueId)
			if err == nil && venue != nil {
				extended.VenueName = venue.Name
				if venue.Images != "" {
					// 解析图片列表，获取第一张图片作为场地图片
					var imageList []string
					err = json.Unmarshal([]byte(venue.Images), &imageList)
					if err == nil && len(imageList) > 0 {
						extended.VenueImage = imageList[0]
					}
				}
			}
		}

		extendedList = append(extendedList, extended)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取预约订单列表成功",
		"data": map[string]interface{}{
			"list":      extendedList,
			"total":     total,
			"page":      page,
			"page_size": pageSize,
		},
	}
	c.ServeJSON()
}

// Detail 获取预约订单详情
func (c *BookingController) Detail() {
	// 获取订单ID
	idStr := c.GetString("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的预约订单ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取预约订单详情
	booking, err := models.GetBookingById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预约订单详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证是否是当前用户的预约订单
	if booking.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权查看该预约订单",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取预约订单详情成功",
		"data":    booking,
	}
	c.ServeJSON()
}

// Cancel 取消预约订单
func (c *BookingController) Cancel() {
	// 解析请求参数
	var req struct {
		Id int64 `json:"id"`
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil || req.Id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取预约订单信息
	booking, err := models.GetBookingById(req.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预约订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证是否是当前用户的预约订单
	if booking.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权取消该预约订单",
		}
		c.ServeJSON()
		return
	}

	// 验证预约订单状态是否可取消
	if booking.Status != 0 && booking.Status != 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "当前状态不可取消",
		}
		c.ServeJSON()
		return
	}

	// 更新预约订单状态为已取消
	booking.Status = models.BookingStatusCancelled // 已取消
	booking.CancelTime = time.Now().Unix()
	booking.UpdatedBy = member.Name

	err = models.UpdateBooking(booking)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "取消预约订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "取消预约订单成功",
	}
	c.ServeJSON()
}

// GetRenewableBookings 获取用户可续订的预约订单列表
func (c *BookingController) GetRenewableBookings() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取查询参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 查询条件
	filters := map[string]interface{}{
		"user_id": member.Id,
		"status":  []int8{models.BookingStatusConfirmed, models.BookingStatusCompleted}, // 只允许已确认和已完成的订单续订
	}

	// 查询订单列表
	bookings, total, err := models.GetBookingList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预约订单列表失败",
		}
		c.ServeJSON()
		return
	}

	// 格式化返回数据
	var resultList []map[string]interface{}
	for _, booking := range bookings {
		// 只返回30天内的订单
		if booking.CreatedAt < time.Now().AddDate(0, 0, -30).Unix() {
			continue
		}

		// 获取场地信息
		venue, err := models.GetVenueById(booking.VenueId)
		if err != nil || venue == nil {
			continue
		}

		// 获取场地所属的门店信息
		store, err := models.GetStoreById(venue.StoreId)
		if err != nil || store == nil {
			continue
		}

		// 格式化状态文本
		statusText := "未知"
		switch booking.Status {
		case models.BookingStatusConfirmed:
			statusText = "已确认"
		case models.BookingStatusCompleted:
			statusText = "已完成"
		}

		// 格式化日期
		startTime := time.Unix(booking.StartTime, 0)
		endTime := time.Unix(booking.EndTime, 0)
		dateStr := startTime.Format("2006-01-02")
		timeRangeStr := startTime.Format("15:04") + "-" + endTime.Format("15:04")

		// 转换价格为元
		totalAmount := float64(booking.TotalAmount) / 100

		resultList = append(resultList, map[string]interface{}{
			"id":           booking.Id,
			"order_no":     booking.OrderNo,
			"venue_id":     booking.VenueId,
			"venue_name":   venue.Name,
			"store_id":     store.Id,
			"store_name":   store.Name,
			"status":       booking.Status,
			"status_text":  statusText,
			"date":         dateStr,
			"time_range":   timeRangeStr,
			"start_time":   booking.StartTime,
			"end_time":     booking.EndTime,
			"total_amount": totalAmount,
			"created_at":   booking.CreatedAt,
		})
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取预约订单列表成功",
		"data": map[string]interface{}{
			"total": total,
			"list":  resultList,
			"page":  page,
		},
	}
	c.ServeJSON()
}

// Renew 创建续订预约订单
func (c *BookingController) Renew() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		VenueId           int64  `json:"venue_id"`
		StartTime         int64  `json:"start_time"`
		EndTime           int64  `json:"end_time"`
		TotalAmount       int64  `json:"total_amount"`
		GroupBuyId        int64  `json:"group_buy_id"`
		CouponId          int64  `json:"coupon_id"`
		UseBalance        int8   `json:"use_balance"`
		BalanceAmount     int64  `json:"balance_amount"`
		Remark            string `json:"remark"`
		OriginalBookingId int64  `json:"original_booking_id"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.VenueId <= 0 || req.StartTime <= 0 || req.EndTime <= 0 || req.StartTime >= req.EndTime || req.OriginalBookingId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "续单参数有误",
		}
		c.ServeJSON()
		return
	}

	// 检查原订单是否存在且属于当前用户
	originalBooking, err := models.GetBookingById(req.OriginalBookingId)
	if err != nil || originalBooking == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原订单不存在",
		}
		c.ServeJSON()
		return
	}

	if originalBooking.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此订单",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(req.VenueId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查时间段是否可预约
	available, message := checkTimeSlotAvailable(req.VenueId, req.StartTime, req.EndTime)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 生成订单号
	orderNo := models.GenerateOrderNo("R") // R表示Renew

	// 计算实际需要支付的金额（总金额减去余额支付部分）
	remainingAmount := req.TotalAmount
	balanceAmount := int64(0)

	// 如果使用余额支付
	if req.UseBalance == 1 && req.BalanceAmount > 0 {
		// 检查会员余额是否足够
		memberBalance := int64(member.Balance * 100) // 转换为分

		// 如果余额不足，使用全部余额
		if memberBalance < req.BalanceAmount {
			balanceAmount = memberBalance
		} else {
			balanceAmount = req.BalanceAmount
		}

		// 计算剩余需要支付的金额
		remainingAmount = req.TotalAmount - balanceAmount
	}

	// 创建预约订单
	booking := &models.Order{
		OrderNo:        orderNo,
		UserId:         member.Id,
		MemberId:       member.Id,
		UserName:       member.Name,
		Phone:          member.Phone,
		Type:           1,                           // 续单类型
		Status:         models.BookingStatusPending, // 待确认
		TotalAmount:    req.TotalAmount,
		PayAmount:      remainingAmount, // 实际需要支付的金额
		PaymentChannel: "",              // 预约订单可能不需要支付
		PaymentStatus:  0,               // 未支付
		VenueId:        req.VenueId,
		StoreId:        venue.StoreId,
		StartTime:      req.StartTime,
		EndTime:        req.EndTime,
		Remark:         req.Remark + " (续单: 原订单号 " + originalBooking.OrderNo + ")",
	}

	// 如果有团购券，处理团购券逻辑
	if req.GroupBuyId > 0 {
		booking.GroupBuyId = req.GroupBuyId
	}

	// 如果有优惠券，处理优惠券逻辑
	if req.CouponId > 0 {
		booking.CouponId = req.CouponId
	}

	// 设置基础字段
	booking.CreatedAt = time.Now().Unix()
	booking.UpdatedAt = booking.CreatedAt
	booking.CreatedBy = member.Name
	booking.UpdatedBy = member.Name

	// 开始事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 创建预约订单
	bookingId, err := models.CreateBookingTx(tx, booking)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建续单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果使用余额，扣减余额
	if req.UseBalance == 1 && balanceAmount > 0 {
		// 扣减余额
		member.Balance -= float64(balanceAmount) / 100
		_, err = tx.Update(member, "Balance", "UpdatedAt")
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "扣减余额失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 添加余额变更记录
		balanceLog := &models.BalanceLog{
			BaseModel: models.BaseModel{
				CreatedAt: time.Now().Unix(),
				UpdatedAt: time.Now().Unix(),
				CreatedBy: member.Name,
				UpdatedBy: member.Name,
			},
			MemberId:      member.Id,
			Amount:        -float64(balanceAmount) / 100,
			BeforeBalance: member.Balance + float64(balanceAmount)/100,
			AfterBalance:  member.Balance,
			Type:          2, // 余额支付
			OrderNo:       orderNo,
			Description:   "续单支付",
			Operator:      member.Name,
		}

		_, err = tx.Insert(balanceLog)
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "记录余额变更失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "续单创建成功",
		"data": map[string]interface{}{
			"booking_id": bookingId,
			"order_no":   orderNo,
		},
	}
	c.ServeJSON()
}

// CreatePreOrder 创建预订单并生成支付参数
func (c *BookingController) CreatePreOrder() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		VenueId       int64  `json:"venue_id"`
		StartTime     int64  `json:"start_time"`
		EndTime       int64  `json:"end_time"`
		TotalAmount   int64  `json:"total_amount"`
		GroupBuyId    int64  `json:"group_buy_id"`
		CouponId      int64  `json:"coupon_id"`
		UseBalance    int8   `json:"use_balance"`
		BalanceAmount int64  `json:"balance_amount"`
		Remark        string `json:"remark"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.VenueId <= 0 || req.StartTime <= 0 || req.EndTime <= 0 || req.StartTime >= req.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预约参数有误",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(req.VenueId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查时间段是否可预约
	available, message := checkTimeSlotAvailable(req.VenueId, req.StartTime, req.EndTime)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 生成预订单号
	preOrderNo := models.GenerateOrderNo("P") // P表示PreOrder

	// 计算实际需要支付的金额（总金额减去余额支付部分）
	remainingAmount := req.TotalAmount
	balanceAmount := int64(0)

	// 如果使用余额支付
	if req.UseBalance == 1 && req.BalanceAmount > 0 {
		// 检查会员余额是否足够
		memberBalance := int64(member.Balance * 100) // 转换为分

		// 如果余额不足，使用全部余额
		if memberBalance < req.BalanceAmount {
			balanceAmount = memberBalance
		} else {
			balanceAmount = req.BalanceAmount
		}

		// 计算剩余需要支付的金额
		remainingAmount = req.TotalAmount - balanceAmount
	}

	// 创建预订单
	preOrder := &models.PreOrder{
		PreOrderNo:     preOrderNo,
		UserId:         member.Id,
		MemberId:       member.Id,
		UserName:       member.Name,
		Phone:          member.Phone,
		Status:         models.PreOrderStatusPending, // 待支付
		TotalAmount:    req.TotalAmount,
		PayAmount:      remainingAmount, // 实际需要支付的金额
		BalanceAmount:  balanceAmount,   // 使用余额部分
		UseBalance:     req.UseBalance,
		PaymentChannel: "wechat", // 默认微信支付
		VenueId:        req.VenueId,
		StoreId:        venue.StoreId,
		StartTime:      req.StartTime,
		EndTime:        req.EndTime,

		Remark:     req.Remark,
		ExpireTime: time.Now().Add(30 * time.Minute).Unix(), // 30分钟有效期
	}

	// 如果有团购券，添加到预订单
	if req.GroupBuyId > 0 {
		preOrder.GroupBuyId = req.GroupBuyId
	}

	// 如果有优惠券，添加到预订单
	if req.CouponId > 0 {
		preOrder.CouponId = req.CouponId
	}

	// 设置基础字段
	preOrder.CreatedAt = time.Now().Unix()
	preOrder.UpdatedAt = preOrder.CreatedAt
	preOrder.CreatedBy = member.Name
	preOrder.UpdatedBy = member.Name

	// 开始事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 创建预订单
	preOrderId, err := models.CreatePreOrderTx(tx, preOrder)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建预订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单详情
	preOrder, err = models.GetPreOrderById(preOrderId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预订单失败",
		}
		c.ServeJSON()
		return
	}

	// 构建返回数据
	result := map[string]interface{}{
		"pre_order_id": preOrderId,
		"pre_order_no": preOrderNo,
	}

	// 如果无需支付（例如，全部使用余额支付），则直接返回
	if remainingAmount <= 0 {
		result["need_pay"] = false
	} else {
		// 生成微信支付参数
		payParams, err := generateWxPayParams(preOrder)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "生成支付参数失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		result["need_pay"] = true
		result["pay_params"] = payParams
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建预订单成功",
		"data":    result,
	}
	c.ServeJSON()
}

// 生成微信支付参数
func generateWxPayParams(preOrder *models.PreOrder) (any, error) {
	// 获取会员信息以获取openId
	member, err := models.GetMemberById(preOrder.MemberId, preOrder.FranchiseId)
	if err != nil {
		return nil, fmt.Errorf("获取会员信息失败: %v", err)
	}

	// 从会员信息中获取openId，如果没有则使用空字符串
	openId := ""
	if member.OpenId != "" {
		openId = member.OpenId
	}
	if preOrder.Remark == "" {
		logs.Debug("remark is empty")
		preOrder.Remark = "小程序预约"
	}
	// 使用wxpay包中的函数生成支付参数
	params, err := utils.GenerateWxPayParams(preOrder.FranchiseId, preOrder.PreOrderNo, preOrder.PayAmount, preOrder.Remark, openId)
	if err != nil {
		return nil, err
	}
	return params, nil
}

// ConfirmOrder 确认订单（支付成功后）
func (c *BookingController) ConfirmOrder() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		PreOrderId int64 `json:"pre_order_id"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.PreOrderId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单信息
	preOrder, err := models.GetPreOrderById(req.PreOrderId)
	if err != nil || preOrder == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否属于当前用户
	if preOrder.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此预订单",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单状态
	if preOrder.Status != models.PreOrderStatusPending {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单状态异常，无法确认",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否过期
	if preOrder.ExpireTime < time.Now().Unix() {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单已过期",
		}
		c.ServeJSON()
		return
	}

	// 生成正式订单号
	orderNo := models.GenerateOrderNo("B") // B表示Booking

	// 创建正式预约订单
	booking := &models.Order{
		OrderNo:        orderNo,
		UserId:         preOrder.UserId,
		MemberId:       preOrder.MemberId,
		UserName:       preOrder.UserName,
		Phone:          preOrder.Phone,
		Type:           0,                             // 普通预约
		Status:         models.BookingStatusConfirmed, // 待确认
		TotalAmount:    preOrder.TotalAmount,
		PayAmount:      preOrder.PayAmount,
		PaymentChannel: preOrder.PaymentChannel,
		PaymentStatus:  1, // 已支付
		VenueId:        preOrder.VenueId,
		StoreId:        preOrder.StoreId,
		StartTime:      preOrder.StartTime,
		EndTime:        preOrder.EndTime,
		Remark:         preOrder.Remark,
		GroupBuyId:     preOrder.GroupBuyId,
		CouponId:       preOrder.CouponId,
	}

	// 设置基础字段
	booking.CreatedAt = time.Now().Unix()
	booking.UpdatedAt = booking.CreatedAt
	booking.CreatedBy = member.Name
	booking.UpdatedBy = member.Name

	// 开始事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 创建正式订单
	bookingId, err := models.CreateBookingTx(tx, booking)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新预订单状态为已确认
	preOrder.Status = models.PreOrderStatusConfirmed
	preOrder.OrderId = bookingId
	preOrder.UpdatedAt = time.Now().Unix()
	preOrder.UpdatedBy = member.Name

	_, err = tx.Update(preOrder)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新预订单状态失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果使用余额，扣减余额
	if preOrder.UseBalance == 1 && preOrder.BalanceAmount > 0 {
		// 扣减余额
		member.Balance -= float64(preOrder.BalanceAmount) / 100
		_, err = tx.Update(member, "Balance", "UpdatedAt")
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "扣减余额失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 添加余额变更记录
		balanceLog := &models.BalanceLog{
			BaseModel: models.BaseModel{
				CreatedAt: time.Now().Unix(),
				UpdatedAt: time.Now().Unix(),
				CreatedBy: member.Name,
				UpdatedBy: member.Name,
			},
			MemberId:      member.Id,
			Amount:        -float64(preOrder.BalanceAmount) / 100,
			BeforeBalance: member.Balance + float64(preOrder.BalanceAmount)/100,
			AfterBalance:  member.Balance,
			Type:          2, // 余额支付
			OrderNo:       orderNo,
			Description:   "预约支付",
			Operator:      member.Name,
		}

		_, err = tx.Insert(balanceLog)
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "记录余额变更失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "预约订单创建成功",
		"data": map[string]interface{}{
			"booking_id": bookingId,
			"order_no":   orderNo,
		},
	}
	c.ServeJSON()
}

// GetPayParams 获取支付参数（用于重新支付）
func (c *BookingController) GetPayParams() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单ID
	preOrderId, err := c.GetInt64("pre_order_id")
	if err != nil || preOrderId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单ID无效",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单信息
	preOrder, err := models.GetPreOrderById(preOrderId)
	if err != nil || preOrder == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否属于当前用户
	if preOrder.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此预订单",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单状态
	if preOrder.Status != models.PreOrderStatusPending {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单状态异常，无法支付",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否过期
	if preOrder.ExpireTime < time.Now().Unix() {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单已过期",
		}
		c.ServeJSON()
		return
	}

	// 如果无需支付（例如，全部使用余额支付），则直接返回
	if preOrder.PayAmount <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "无需支付",
			"data": map[string]interface{}{
				"need_pay":     false,
				"pre_order_id": preOrder.Id,
				"pre_order_no": preOrder.PreOrderNo,
			},
		}
		c.ServeJSON()
		return
	}

	// 生成微信支付参数
	payParams, err := generateWxPayParams(preOrder)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "生成支付参数失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取支付参数成功",
		"data": map[string]interface{}{
			"need_pay":     true,
			"pay_params":   payParams,
			"pre_order_id": preOrder.Id,
			"pre_order_no": preOrder.PreOrderNo,
		},
	}
	c.ServeJSON()
}

// RenewPreOrder 创建续单预订单并生成支付参数
func (c *BookingController) RenewPreOrder() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		VenueId           int64  `json:"venue_id"`
		StartTime         int64  `json:"start_time"`
		EndTime           int64  `json:"end_time"`
		TotalAmount       int64  `json:"total_amount"`
		GroupBuyId        int64  `json:"group_buy_id"`
		CouponId          int64  `json:"coupon_id"`
		UseBalance        int8   `json:"use_balance"`
		BalanceAmount     int64  `json:"balance_amount"`
		Remark            string `json:"remark"`
		OriginalBookingId int64  `json:"original_booking_id"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.VenueId <= 0 || req.StartTime <= 0 || req.EndTime <= 0 || req.StartTime >= req.EndTime || req.OriginalBookingId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "续单参数有误",
		}
		c.ServeJSON()
		return
	}

	// 检查原订单是否存在且属于当前用户
	originalBooking, err := models.GetBookingById(req.OriginalBookingId)
	if err != nil || originalBooking == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原订单不存在",
		}
		c.ServeJSON()
		return
	}

	if originalBooking.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此订单",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(req.VenueId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查时间段是否可预约
	available, message := checkTimeSlotAvailable(req.VenueId, req.StartTime, req.EndTime)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 生成预订单号
	preOrderNo := models.GenerateOrderNo("PR") // PR表示PreRenew

	// 计算实际需要支付的金额（总金额减去余额支付部分）
	remainingAmount := req.TotalAmount
	balanceAmount := int64(0)

	// 如果使用余额支付
	if req.UseBalance == 1 && req.BalanceAmount > 0 {
		// 检查会员余额是否足够
		memberBalance := int64(member.Balance * 100) // 转换为分

		// 如果余额不足，使用全部余额
		if memberBalance < req.BalanceAmount {
			balanceAmount = memberBalance
		} else {
			balanceAmount = req.BalanceAmount
		}

		// 计算剩余需要支付的金额
		remainingAmount = req.TotalAmount - balanceAmount
	}

	// 创建预订单
	preOrder := &models.PreOrder{
		PreOrderNo:        preOrderNo,
		UserId:            member.Id,
		MemberId:          member.Id,
		UserName:          member.Name,
		Phone:             member.Phone,
		Status:            models.PreOrderStatusPending, // 待支付
		TotalAmount:       req.TotalAmount,
		PayAmount:         remainingAmount, // 实际需要支付的金额
		BalanceAmount:     balanceAmount,   // 使用余额部分
		UseBalance:        req.UseBalance,
		PaymentChannel:    "wechat", // 默认微信支付
		VenueId:           req.VenueId,
		StoreId:           venue.StoreId,
		StartTime:         req.StartTime,
		EndTime:           req.EndTime,
		Remark:            req.Remark,
		ExpireTime:        time.Now().Add(30 * time.Minute).Unix(), // 30分钟有效期
		Type:              1,                                       // 续单类型
		OriginalBookingId: req.OriginalBookingId,
	}

	// 如果有团购券，添加到预订单
	if req.GroupBuyId > 0 {
		preOrder.GroupBuyId = req.GroupBuyId
	}

	// 如果有优惠券，添加到预订单
	if req.CouponId > 0 {
		preOrder.CouponId = req.CouponId
	}

	// 设置基础字段
	preOrder.CreatedAt = time.Now().Unix()
	preOrder.UpdatedAt = preOrder.CreatedAt
	preOrder.CreatedBy = member.Name
	preOrder.UpdatedBy = member.Name

	// 开始事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 创建预订单
	preOrderId, err := models.CreatePreOrderTx(tx, preOrder)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建预订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单详情
	preOrder, err = models.GetPreOrderById(preOrderId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预订单失败",
		}
		c.ServeJSON()
		return
	}

	// 构建返回数据
	result := map[string]interface{}{
		"pre_order_id": preOrderId,
		"pre_order_no": preOrderNo,
	}

	// 如果无需支付（例如，全部使用余额支付），则直接返回
	if remainingAmount <= 0 {
		result["need_pay"] = false
	} else {
		// 生成微信支付参数
		payParams, err := generateWxPayParams(preOrder)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "生成支付参数失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		result["need_pay"] = true
		result["pay_params"] = payParams
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建续单预订单成功",
		"data":    result,
	}
	c.ServeJSON()
}

// ConfirmRenewOrder 确认续单订单（支付成功后）
func (c *BookingController) ConfirmRenewOrder() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		PreOrderId int64 `json:"pre_order_id"`
	}

	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.PreOrderId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单信息
	preOrder, err := models.GetPreOrderById(req.PreOrderId)
	if err != nil || preOrder == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否属于当前用户
	if preOrder.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此预订单",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单状态
	if preOrder.Status != models.PreOrderStatusPending {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单状态异常，无法确认",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否过期
	if preOrder.ExpireTime < time.Now().Unix() {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单已过期",
		}
		c.ServeJSON()
		return
	}

	// 检查是否为续单类型
	if preOrder.Type != 1 || preOrder.OriginalBookingId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "非续单预订单",
		}
		c.ServeJSON()
		return
	}

	// 获取原订单
	originalBooking, err := models.GetBookingById(preOrder.OriginalBookingId)
	if err != nil || originalBooking == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 生成正式订单号
	orderNo := models.GenerateOrderNo("R") // R表示Renew

	// 创建正式预约订单
	booking := &models.Order{
		OrderNo:        orderNo,
		UserId:         preOrder.UserId,
		MemberId:       preOrder.MemberId,
		UserName:       preOrder.UserName,
		Phone:          preOrder.Phone,
		Type:           1,                           // 续单类型
		Status:         models.BookingStatusPending, // 待确认
		TotalAmount:    preOrder.TotalAmount,
		PayAmount:      preOrder.PayAmount,
		PaymentChannel: preOrder.PaymentChannel,
		PaymentStatus:  1, // 已支付
		VenueId:        preOrder.VenueId,
		StoreId:        preOrder.StoreId,
		StartTime:      preOrder.StartTime,
		EndTime:        preOrder.EndTime,
		Remark:         preOrder.Remark + " (续单: 原订单号 " + originalBooking.OrderNo + ")",
		GroupBuyId:     preOrder.GroupBuyId,
		CouponId:       preOrder.CouponId,
	}

	// 设置基础字段
	booking.CreatedAt = time.Now().Unix()
	booking.UpdatedAt = booking.CreatedAt
	booking.CreatedBy = member.Name
	booking.UpdatedBy = member.Name

	// 开始事务处理
	o := models.GetOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 创建正式订单
	bookingId, err := models.CreateBookingTx(tx, booking)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建续单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新预订单状态为已确认
	preOrder.Status = models.PreOrderStatusConfirmed
	preOrder.OrderId = bookingId
	preOrder.UpdatedAt = time.Now().Unix()
	preOrder.UpdatedBy = member.Name

	_, err = tx.Update(preOrder)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新预订单状态失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果使用余额，扣减余额
	if preOrder.UseBalance == 1 && preOrder.BalanceAmount > 0 {
		// 扣减余额
		member.Balance -= float64(preOrder.BalanceAmount) / 100
		_, err = tx.Update(member, "Balance", "UpdatedAt")
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "扣减余额失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 添加余额变更记录
		balanceLog := &models.BalanceLog{
			BaseModel: models.BaseModel{
				CreatedAt: time.Now().Unix(),
				UpdatedAt: time.Now().Unix(),
				CreatedBy: member.Name,
				UpdatedBy: member.Name,
			},
			MemberId:      member.Id,
			Amount:        -float64(preOrder.BalanceAmount) / 100,
			BeforeBalance: member.Balance + float64(preOrder.BalanceAmount)/100,
			AfterBalance:  member.Balance,
			Type:          2, // 余额支付
			OrderNo:       orderNo,
			Description:   "续单支付",
			Operator:      member.Name,
		}

		_, err = tx.Insert(balanceLog)
		if err != nil {
			tx.Rollback()
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "记录余额变更失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误，请稍后再试",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "续单创建成功",
		"data": map[string]interface{}{
			"booking_id": bookingId,
			"order_no":   orderNo,
		},
	}
	c.ServeJSON()
}

// PayNotify 支付成功通知处理
func (c *BookingController) PayNotify() {
	// 解析支付回调数据
	var notifyData struct {
		PreOrderNo string `json:"pre_order_no"`
		Status     string `json:"status"`
		TradeNo    string `json:"trade_no"`
	}

	err := json.NewDecoder(c.Ctx.Request.Body).Decode(&notifyData)
	if err != nil {
		logs.Error("支付通知解析失败: %v", err)
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 验证必要的字段
	if notifyData.PreOrderNo == "" || notifyData.Status == "" {
		logs.Error("支付通知缺少必要字段")
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 获取预订单信息
	preOrder, err := models.GetPreOrderByOrderNo(notifyData.PreOrderNo)
	if err != nil || preOrder == nil {
		logs.Error("获取预订单失败: %v", err)
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 判断是否已经处理过
	if preOrder.Status != models.PreOrderStatusPending {
		logs.Warn("预订单[%s]已处理，状态为: %d", notifyData.PreOrderNo, preOrder.Status)
		c.Ctx.ResponseWriter.WriteHeader(200)
		c.Ctx.WriteString("SUCCESS")
		return
	}

	// 开始事务
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		logs.Error("开始事务失败: %v", err)
		c.Ctx.ResponseWriter.WriteHeader(500)
		c.Ctx.WriteString("FAIL")
		return
	}

	var bookingId int64
	// 根据预订单类型进行不同处理
	if preOrder.Type == 0 { // 普通预约
		// 创建正式订单
		booking := &models.Order{
			OrderNo:        utils.GenerateOrderNo("BK"),
			UserId:         preOrder.UserId,
			MemberId:       preOrder.MemberId,
			UserName:       preOrder.UserName,
			Phone:          preOrder.Phone,
			Status:         models.BookingStatusConfirmed,
			TotalAmount:    preOrder.TotalAmount,
			PayAmount:      preOrder.PayAmount,
			BalanceAmount:  preOrder.BalanceAmount,
			UseBalance:     preOrder.UseBalance,
			PaymentChannel: "wechat",
			TradeNo:        notifyData.TradeNo,
			VenueId:        preOrder.VenueId,
			StoreId:        preOrder.StoreId,
			StartTime:      preOrder.StartTime,
			EndTime:        preOrder.EndTime,
			CouponId:       preOrder.CouponId,
			GroupBuyId:     preOrder.GroupBuyId,
			Remark:         preOrder.Remark,
		}
		// 设置兼容字段
		booking.Type = 0
		booking.PaymentStatus = 1 // 已支付
		booking.PaymentTime = time.Now().Unix()

		booking.BeforeInsert()
		bookingId, err = tx.Insert(booking)
		if err != nil {
			tx.Rollback()
			logs.Error("创建正式订单失败: %v", err)
			c.Ctx.ResponseWriter.WriteHeader(500)
			c.Ctx.WriteString("FAIL")
			return
		}
	} else if preOrder.Type == 1 { // 续单
		// 创建续单订单
		booking := &models.Order{
			OrderNo:           utils.GenerateOrderNo("RN"),
			UserId:            preOrder.UserId,
			MemberId:          preOrder.MemberId,
			UserName:          preOrder.UserName,
			Phone:             preOrder.Phone,
			Status:            models.BookingStatusConfirmed,
			TotalAmount:       preOrder.TotalAmount,
			PayAmount:         preOrder.PayAmount,
			BalanceAmount:     preOrder.BalanceAmount,
			UseBalance:        preOrder.UseBalance,
			PaymentChannel:    "wechat",
			TradeNo:           notifyData.TradeNo,
			VenueId:           preOrder.VenueId,
			StoreId:           preOrder.StoreId,
			StartTime:         preOrder.StartTime,
			EndTime:           preOrder.EndTime,
			CouponId:          preOrder.CouponId,
			GroupBuyId:        preOrder.GroupBuyId,
			Remark:            preOrder.Remark,
			OriginalBookingId: preOrder.OriginalBookingId,
			IsRenew:           1, // 标记为续单
		}
		// 设置兼容字段
		booking.Type = 1
		booking.PaymentStatus = 1 // 已支付
		booking.PaymentTime = time.Now().Unix()

		booking.BeforeInsert()
		bookingId, err = tx.Insert(booking)
		if err != nil {
			tx.Rollback()
			logs.Error("创建续单订单失败: %v", err)
			c.Ctx.ResponseWriter.WriteHeader(500)
			c.Ctx.WriteString("FAIL")
			return
		}
	} else {
		tx.Rollback()
		logs.Error("未知的预订单类型: %d", preOrder.Type)
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 更新预订单状态
	preOrder.Status = models.PreOrderStatusConfirmed
	preOrder.OrderId = bookingId
	_, err = tx.Update(preOrder)
	if err != nil {
		tx.Rollback()
		logs.Error("更新预订单状态失败: %v", err)
		c.Ctx.ResponseWriter.WriteHeader(500)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 处理优惠券使用
	if preOrder.CouponId > 0 {
		err = models.UseCouponTx(tx, preOrder.CouponId, preOrder.UserId, bookingId)
		if err != nil {
			tx.Rollback()
			logs.Error("使用优惠券失败: %v", err)
			c.Ctx.ResponseWriter.WriteHeader(500)
			c.Ctx.WriteString("FAIL")
			return
		}
	}

	// 处理团购券使用
	if preOrder.GroupBuyId > 0 {
		err = models.UseGroupBuyTx(tx, preOrder.GroupBuyId, preOrder.UserId, bookingId)
		if err != nil {
			tx.Rollback()
			logs.Error("使用团购券失败: %v", err)
			c.Ctx.ResponseWriter.WriteHeader(500)
			c.Ctx.WriteString("FAIL")
			return
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		logs.Error("提交事务失败: %v", err)
		c.Ctx.ResponseWriter.WriteHeader(500)
		c.Ctx.WriteString("FAIL")
		return
	}

	// 返回成功
	c.Ctx.ResponseWriter.WriteHeader(200)
	c.Ctx.WriteString("SUCCESS")
}
